package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.http.base.Log;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import logic.bean.OrderFoodListBean;
import logic.bean.OrderTakeOutOrderBean;
import logic.util.MoneyUtil;
import logic.util.Utils;


public class MyTakeoutDetailActivity extends BaseBusinessActivity implements OnClickListener {
    private TextView tvTitle, tvUse, tvNotPayed, tvShopName, tvJineTxt, tvJineValue, tvVoucharValue, tvMinusValue;
    private TextView tvTable1, tvTable2, tvTable3, tvTable4;
    private TextView tvPayValue, tvOrderId, tvOrderTime, tvOrderPayType, tvPhone, tvAddress;
    private TextView tvTopStatus;
    private View topView, wholeView, rlVouchar, vVoucharDivider, rlMinus, vMinusDivider, rlPayValue, vPayValueDivider;
    private ImageView ivCall, ivTable1, ivTable2, ivTable3, ivTable4;
    private Button btnBack;
    private ListView lvFood;
    private LoadingView loadingView;

    private MyAdapter adapter;
    private List<OrderFoodListBean> foodList = new ArrayList<OrderFoodListBean>();
    private Context context;
    private OrderTakeOutOrderBean orderBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        long orderId = getIntent().getExtras().getLong("orderId");
        initView();
        initLoadingView();
        initData(orderId);
        setListener();
    }

    private void initView() {
        View view = LayoutInflater.from(context).inflate(R.layout.my_takeout_detail_lay, null);
        setContentView(view);
        tvTitle = (TextView) view.findViewById(R.id.common_header_name);
        tvTitle.setText("外卖详情");
        btnBack = (Button) view.findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        wholeView = view.findViewById(R.id.my_takeout_detail_view);
        loadingView = (LoadingView) view.findViewById(R.id.om_my_appointment_loading_view);
        topView = view.findViewById(R.id.my_takeout_detail_top_ll);
        tvTopStatus = (TextView) view.findViewById(R.id.tv_om_pay_finish_finish);
        tvUse = (TextView) view.findViewById(R.id.tv_om_pay_finish_finish_wait);
        tvUse.setText("感谢您使用" + getResources().getString(R.string.app_name) + "!");
        tvNotPayed = (TextView) view.findViewById(R.id.tv_om_pay_finish_not_payed);
        ivTable1 = (ImageView) view.findViewById(R.id.iv_om_pay_finish_commit);
        ivTable2 = (ImageView) view.findViewById(R.id.iv_om_pay_finish_accepted);
        ivTable3 = (ImageView) view.findViewById(R.id.iv_om_pay_finish_sent);
        ivTable4 = (ImageView) view.findViewById(R.id.iv_om_pay_finish_received);
        tvTable1 = (TextView) view.findViewById(R.id.tv_om_pay_finish_commited);
        tvTable2 = (TextView) view.findViewById(R.id.tv_om_pay_finish_accepted);
        tvTable3 = (TextView) view.findViewById(R.id.tv_om_pay_finish_sent);
        tvTable4 = (TextView) view.findViewById(R.id.tv_om_pay_finish_received);
        tvShopName = (TextView) view.findViewById(R.id.my_takeout_detail_shopname_tv);
        ivCall = (ImageView) view.findViewById(R.id.my_takeout_detail_call_img);
        tvJineTxt = (TextView) view.findViewById(R.id.my_takeout_detail_jine_txt);
        tvJineValue = (TextView) view.findViewById(R.id.my_takeout_detail_jine_value_txt);
        tvVoucharValue = (TextView) view.findViewById(R.id.my_takeout_detail_vouchar_value_txt);
        tvMinusValue = (TextView) view.findViewById(R.id.my_takeout_detail_minus_value_txt);
        tvPayValue = (TextView) view.findViewById(R.id.my_takeout_detail_pay_value_txt);
        tvOrderId = (TextView) view.findViewById(R.id.my_takeout_detail_order_id_value_txt);
        tvOrderTime = (TextView) view.findViewById(R.id.my_takeout_detail_order_time_value_txt);
        tvOrderPayType = (TextView) view.findViewById(R.id.my_takeout_detail_order_paytype_value_txt);
        tvPhone = (TextView) view.findViewById(R.id.my_takeout_detail_order_phone_value_txt);
        tvAddress = (TextView) view.findViewById(R.id.my_takeout_detail_order_address_value_txt);
        rlVouchar = view.findViewById(R.id.my_takeout_detail_vouchar_rl);
        rlMinus = view.findViewById(R.id.my_takeout_detail_minus_rl);
        rlPayValue = view.findViewById(R.id.my_takeout_detail_pay_value_rl);
        vVoucharDivider = view.findViewById(R.id.my_takeout_detail_vouchar_divider);
        vMinusDivider = view.findViewById(R.id.my_takeout_detail_minus_divider);
        vPayValueDivider = view.findViewById(R.id.my_takeout_detail_pay_value_divider);
        lvFood = (ListView) view.findViewById(R.id.my_takeout_detail_list);
        adapter = new MyAdapter();
        lvFood.setAdapter(adapter);
    }

    private void initLoadingView() {
        loadingView.setLoadingAnim(R.drawable.home_progress);
        ImageView imageView = new ImageView(context);
        imageView.setImageResource(R.drawable.home_loading_fail);
        loadingView.setFailView(imageView);
        loadingView.changeLoadingStatus(0);
        loadingView.setVisibility(View.VISIBLE);
        wholeView.setVisibility(View.GONE);
        //			loadingView.setEmptyView(R.drawable.bg_region_blank, R.string.order_appointment_empty_text);//重新设置为空的图片和文案
    }

    private void initTopUI() {
        switch (Integer.parseInt(orderBean.getStatus())) {
            case 0://未付款
                topView.setVisibility(View.GONE);
                tvNotPayed.setVisibility(View.VISIBLE);
                tvNotPayed.setText("感谢您使用" + getResources().getString(R.string.app_name) + "，您的订单未支付完成，\n请在30分钟内付款。");
                break;
            case 1://订单提交
                tvTopStatus.setText("订单提交");
                tvUse.setText("感谢您使用" + getResources().getString(R.string.app_name) + "，我们正在努力配菜中...");
                ivTable1.setImageResource(R.drawable.om_pay_finish_commit_already);
                tvTable1.setTextColor(Color.parseColor("#323232"));
                break;
            case 2://配送中
                tvTopStatus.setText("配送中");
                tvUse.setText("感谢您使用" + getResources().getString(R.string.app_name) + "，外送小哥正在离你越来越近...");
                ivTable1.setImageResource(R.drawable.om_pay_finish_commit_already);
                ivTable2.setImageResource(R.drawable.om_pay_finish_accepted_already);
                ivTable3.setImageResource(R.drawable.om_pay_finish_sent_already);
                tvTable1.setTextColor(Color.parseColor("#323232"));
                tvTable2.setTextColor(Color.parseColor("#323232"));
                tvTable3.setTextColor(Color.parseColor("#323232"));
                break;
            case 3:
            case 4:
                tvTopStatus.setText("订单完成");
                tvUse.setText("感谢您使用" + getResources().getString(R.string.app_name) + "！");
                ivTable1.setImageResource(R.drawable.om_pay_finish_commit_already);
                ivTable2.setImageResource(R.drawable.om_pay_finish_accepted_already);
                ivTable3.setImageResource(R.drawable.om_pay_finish_sent_already);
                ivTable4.setImageResource(R.drawable.om_pay_finish_received_already);
                tvTable1.setTextColor(Color.parseColor("#323232"));
                tvTable2.setTextColor(Color.parseColor("#323232"));
                tvTable3.setTextColor(Color.parseColor("#323232"));
                tvTable4.setTextColor(Color.parseColor("#323232"));
                break;
            case 5:
                topView.setBackgroundColor(0xff998e7a);
                tvTopStatus.setText("取消订单");
                //				if (orderBean.getPayType() == 1)
                //				{
                //					//在线支付
                //					tvUse.setText("感谢您使用" + getResources().getString(R.string.app_name) + "，退款已完成");
                //				}
                //				else
                //				{
                //餐到付款
                tvUse.setText("感谢您使用" + getResources().getString(R.string.app_name) + "，订单已取消!");
                //				}
                break;
            case 6://餐厅接单
                tvTopStatus.setText("餐厅接单");
                tvUse.setText("感谢您使用" + getResources().getString(R.string.app_name) + "，厨师大哥正在速度烧菜中...");
                ivTable1.setImageResource(R.drawable.om_pay_finish_commit_already);
                ivTable2.setImageResource(R.drawable.om_pay_finish_accepted_already);
                tvTable1.setTextColor(Color.parseColor("#323232"));
                tvTable2.setTextColor(Color.parseColor("#323232"));
                break;
        }
    }

    private void initUI() {
        loadingView.setVisibility(View.GONE);
        wholeView.setVisibility(View.VISIBLE);
        foodList = orderBean.getFoodsList();
        Utils.setListViewHeightBasedOnChildren(lvFood, adapter);
        adapter.notifyDataSetChanged();
        tvShopName.setText(orderBean.getStoreDto().getName());
        tvJineTxt.setText(orderBean.getExpressMoney() == 0 ? "" : "(含配送费¥" + (double) orderBean.getExpressMoney() / 100 + ")");
        boolean hasCoupon = false;
        boolean hasMinus = false;
        if (orderBean.getCouponFreeMoney() == 0) {
            vVoucharDivider.setVisibility(View.GONE);
            rlVouchar.setVisibility(View.GONE);
        } else {
            hasCoupon = true;
            tvVoucharValue.setText("-¥" + (double) orderBean.getCouponFreeMoney() / 100);
        }
        int subtract = 0;
        if (orderBean.getActivityList() == null || orderBean.getActivityList().size() == 0) {
            rlMinus.setVisibility(View.GONE);
            vMinusDivider.setVisibility(View.GONE);
        } else {
            for (int i = 0; i < orderBean.getActivityList().size(); i++) {
                if (orderBean.getActivityList().get(i).getType() == 1) {
                    hasMinus = true;
                    subtract = orderBean.getActivityList().get(i).getDetail().get(0).getSubtract();
                    tvMinusValue.setText("-¥" + Utils.getOneMoneyFormat(MoneyUtil.divide(subtract, 100)));
                }
            }
            if (!hasMinus) {
                rlMinus.setVisibility(View.GONE);
                vMinusDivider.setVisibility(View.GONE);
            }
        }
        tvJineValue.setText("¥" + (double) (orderBean.getCouponFreeMoney() + orderBean.getActualMoney() + subtract) / 100);
        if (hasCoupon || hasMinus) {
            tvPayValue.setText("¥" + ((double) orderBean.getActualMoney() / 100));
        } else {
            vPayValueDivider.setVisibility(View.GONE);
            rlPayValue.setVisibility(View.GONE);
        }
        tvOrderId.setText("" + orderBean.getOrderSerial());
        tvOrderTime.setText(formatTime(orderBean.getCreateTime()));
        tvOrderPayType.setText(orderBean.getPayType() == 1 ? "在线支付" : "餐到付款");
        tvPhone.setText(orderBean.getDeliveryAddress().getPhone());
        tvAddress.setText(orderBean.getDeliveryAddress().getProvinceName() + orderBean.getDeliveryAddress().getCityName() + orderBean.getDeliveryAddress().getAreaName() + orderBean.getDeliveryAddress().getDetailAddress());
        initTopUI();
    }

    ;

    private String formatTime(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdf.format(new Date(time));
    }

    void initData(long orderId) {
        NewActionHelp.qryOrderDetailWithTakeAway(context, orderId, new ObjectHttpResponseHandler<OrderTakeOutOrderBean>() {

            @Override
            public Type getType() {
                return new TypeToken<OrderTakeOutOrderBean>() {
                }.getType();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
                Log.e(arg2);
                loadingView.changeLoadingStatus(-1);
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, final OrderTakeOutOrderBean arg2, String arg3) {
                Log.i(arg3);
                getUIHandler().post(new Runnable() {

                    @Override
                    public void run() {
                        orderBean = arg2;
                        initUI();
                    }
                });
            }
        });
    }

    private void setListener() {
        btnBack.setOnClickListener(this);
        ivCall.setOnClickListener(this);
    }

    private class MyAdapter
            extends
            BaseAdapter {

        @Override
        public int getCount() {
            return foodList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(context, R.layout.om_confirm_order_list_item, null);
                holder.tvOrderName = (TextView) convertView.findViewById(R.id.tv_om_confirm_order_list_item_name);
                holder.tvOrderNumber = (TextView) convertView.findViewById(R.id.tv_om_confirm_order_list_item_number);
                holder.tvOrderMoney = (TextView) convertView.findViewById(R.id.tv_om_confirm_order_list_item_money);
                holder.tvOrderMoney.setTextColor(0xff8c8c8c);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tvOrderName.setText(foodList.get(position).getFoodName());
            int orderNumber = foodList.get(position).getBuyNum();
            holder.tvOrderNumber.setText("×" + orderNumber);
            if (Utils.isNotEmpty(foodList.get(position).getHasActivity()) && foodList.get(position).getHasActivity().equals("y")) {
                holder.tvOrderMoney.setText("¥" + Utils.getOneMoneyFormat(MoneyUtil.divide(foodList.get(position).getActivityPrice() * orderNumber, 100)));
            } else {
                holder.tvOrderMoney.setText("¥" + Utils.getOneMoneyFormat(MoneyUtil.divide(foodList.get(position).getPrice() * orderNumber, 100)));
            }
            return convertView;
        }

    }

    private class ViewHolder {
        private TextView tvOrderName;
        private TextView tvOrderNumber;
        private TextView tvOrderMoney;
    }

    @Override
    public Handler getUIHandler() {
        return new Handler();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                finish();
                break;
            case R.id.my_takeout_detail_call_img:
                String phone = orderBean.getStoreDto().getContactPhone();
                if (Utils.isNotEmpty(phone)) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:" + phone));
                    startActivity(intent);
                } else {
                    return;
                }
                break;
        }
    }
}
